package com.sservice.web.controller.common;

import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.Msg;
import com.sservice.common.Constants;
import com.sservice.service.service.Redis;
import com.sservice.web.controller.admin.CaptchaController;
import com.sservice.web.utils.JavaSmsApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by suweiming on 2017/12/20.
 */

@Controller
public class Code {
    @Autowired
    Redis redis;
    private Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    /**
     * 短信验证码
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "phone-code")
    public BaseResult<Object> getSmsCode(HttpServletRequest request, String phone) {

        String capText = Constants.generateSmsCode();
        request.getSession().setAttribute(Constants.PHONE_CODE, capText);
        //-- // --
        redis.set(phone, capText);
        logger.debug(request.getSession().getAttribute(Constants.PHONE_CODE).toString()); //
        try {
            return new BaseResult(true, JavaSmsApi.sender(capText, phone));//
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("发送短信验证码异常: " + capText);
        }
        return new BaseResult(true, "success", 200);
    }

    @ResponseBody
    @RequestMapping(value = "sendMsg")
    public BaseResult<Object> sendMsg(HttpSession session) {
        Msg msg = (Msg) session.getAttribute(Msg.KEY);
        if (msg == null) {
            return new BaseResult(false, "非法操作", 403);
        }
        try {
            return new BaseResult(true, JavaSmsApi.sender(msg.getMsg(), msg.getPhone()));
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("发送短信验证码异常: " + msg.getMsg());
        }
        return new BaseResult(true, "success", 200);
    }

}
